<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <!-- 警告区域 -->
      <el-alert title="注意：只允许为第三级分类设置相关参数！" type="warning" effect="dark" show-icon></el-alert>
      <!-- cascader区域 -->
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类：</span>
          <el-cascader
            v-model="selectedKeys"
            :options="cateList"
            :props="cascderProps"
            expandTrigger="hover"
            @change="handleCateChanged"
            clearable
          ></el-cascader>
        </el-col>
        <el-col>
          <!-- TAB卡片选项区域 -->
          <el-tabs type="border-card" v-model="activeName" @tab-click="handleTabClick">
            <!-- 动态参数的面板 -->
            <el-tab-pane label="动态参数" name="many">
              <el-button
                size="mini"
                type="primary"
                :disabled="isDisabled"
                @click="addParamsBtn"
              >添加参数</el-button>
              <!-- 动态参数表格 -->
              <el-table :data="manyTableData" border stripe>
                <!-- 展开行列 -->
                <el-table-column type="expand" label="展开">
                  <!-- 展开插槽 -->
                  <template slot-scope="scope">
                    <!-- 循环渲染tag标签 -->
                    <el-tag
                      v-for="(item,index) in scope.row.attr_vals"
                      :key="index"
                      closable
                      @close="closeTag(index,scope.row)"
                    >{{item}}</el-tag>
                    <!-- 输入文本框 -->
                    <el-input
                      class="new_input"
                      v-if="scope.row.inputBtn"
                      v-model="scope.row.inputValue"
                      ref="saveTagInput"
                      @keyup.enter.native="handleInputConfirm(scope.row)"
                      @blur="handleInputConfirm(scope.row)"
                    ></el-input>
                    <!-- newtag添加按钮 -->
                    <el-button
                      v-else
                      class="button-new-tag"
                      size="small"
                      @click="newTagBtn(scope.row)"
                    >+ New Tag</el-button>
                  </template>
                </el-table-column>
                <!-- 索引列 -->
                <el-table-column type="index" label="序号"></el-table-column>
                <!-- 参数名称列 -->
                <el-table-column label="参数名称" prop="attr_name"></el-table-column>
                <!-- 操作列 -->
                <el-table-column label="操作">
                  <!-- 操作插槽 -->
                  <template slot-scope="scope">
                    <el-button
                      size="mini"
                      type="primary"
                      icon="el-icon-edit"
                      @click="editParamsBtn(scope.row.attr_id)"
                    >编辑</el-button>
                    <el-button
                      size="mini"
                      type="danger"
                      icon="el-icon-delet"
                      @click="deleteParamsBtn(scope.row.attr_id)"
                    >删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
            <!-- 静态参数的面板 -->
            <el-tab-pane label="静态属性" name="only">
              <el-button
                size="mini"
                type="primary"
                :disabled="isDisabled"
                @click="addParamsBtn"
              >添加属性</el-button>
              <!-- 静态属性表格 -->
              <el-table :data="onlyTableData" border stripe>
                <!-- 展开行列 -->
                <el-table-column type="expand" label="展开">
                  <!-- 展开插槽 -->
                  <template slot-scope="scope">
                    <!-- 循环渲染tag标签 -->
                    <el-tag
                      v-for="(item,index) in scope.row.attr_vals"
                      :key="index"
                      closable
                      @close="closeTag(index,scope.row)"
                    >{{item}}</el-tag>
                    <!-- 输入文本框 -->
                    <el-input
                      class="new_input"
                      v-if="scope.row.inputBtn"
                      v-model="scope.row.inputValue"
                      ref="saveTagInput"
                      @keyup.enter.native="handleInputConfirm(scope.row)"
                      @blur="handleInputConfirm(scope.row)"
                    ></el-input>
                    <!-- newtag添加按钮 -->
                    <el-button
                      v-else
                      class="button-new-tag"
                      size="small"
                      @click="newTagBtn(scope.row)"
                    >+ New Tag</el-button>
                  </template>
                </el-table-column>
                <!-- 索引列 -->
                <el-table-column type="index" label="序号"></el-table-column>
                <!-- 参数名称列 -->
                <el-table-column label="属性名称" prop="attr_name"></el-table-column>
                <!-- 操作列 -->
                <el-table-column label="操作">
                  <!-- 插槽 -->
                  <template slot-scope="scope">
                    <el-button
                      size="mini"
                      type="primary"
                      icon="el-icon-edit"
                      @click="editParamsBtn(scope.row.attr_id)"
                    >编辑</el-button>
                    <el-button
                      size="mini"
                      type="danger"
                      icon="el-icon-delet"
                      @click="deleteParamsBtn(scope.row.attr_id)"
                    >删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
          </el-tabs>
        </el-col>
      </el-row>
    </el-card>
    <!-- 添加参数对话框 -->
    <el-dialog
      :title="'添加'+titleText"
      :visible.sync="addParamsVisible"
      width="50%"
      @close="addParamsClosed"
    >
      <el-form
        :model="addParamsForm"
        :rules="addParamsRules"
        ref="addParamsRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addParamsVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParamsInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑参数对话框 -->
    <el-dialog
      :title="'修改'+titleText"
      :visible.sync="editParamsVisible"
      width="50%"
      @close="editParamsClosed"
    >
      <el-form
        :model="editParamsForm"
        :rules="editParamsRules"
        ref="editParamsRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editParamsVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParamsInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 商品分类数据
      cateList: [],
      selectedKeys: [],
      cascderProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
      },
      // TAB页签激活显示的页签项
      activeName: 'many',
      // 用来保存动态参数数据
      manyTableData: [],
      // 用来保存静态参数数据
      onlyTableData: [],
      // 添加参数的显示与隐藏
      addParamsVisible: false,
      // 添加参数的动态绑定数据
      addParamsForm: {
        attr_name: '',
      },
      // 添加参数的规则
      addParamsRules: {
        attr_name: [
          { required: true, message: '请输入参数名称！', trigger: 'blur' },
        ],
      },
      editParamsVisible: false,
      editParamsForm: {},
      editParamsRules: {
        attr_name: [
          { required: true, message: '请输入参数名称！', trigger: 'blur' },
        ],
      },
    }
  },
  created() {
    // 打开页面即渲染商品分类的信息到级联选择器中
    this.getParamsList()
  },
  methods: {
    // 发送请求获取商品分类数据
    async getParamsList() {
      const { data: res } = await this.$http.get(`categories`)
      if (res.meta.status !== 200) return res.$message.error(res.meta.msg)
      this.cateList = res.data
    },
    // 级联选择框选中项发生变化时 出触发这个函数
    async handleCateChanged() {
      // 证明选中的不是三级分类
      if (this.selectedKeys.length !== 3) {
        this.selectedKeys = []
        this.manyTableData = []
        this.onlyTableData = []
        return
      }
      // 发送请求根据用户选择的三级分类和面板来获取数据
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: { sel: this.activeName },
        }
      )
      // 错误优先判断
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      // 获取数据成功 先将res.data.attr_vals转换成数组 便于上面去遍历渲染 获取过来的是字符串
      res.data.forEach((item) => {
        // 通过forEach循环将字符串转换为数组
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        // 控制input标签的显示与隐藏
        item.inputBtn = false
        // 文本框中输入的值
        item.inputValue = ''
      })

      if (this.activeName === 'many') {
        // 动态参数数据
        this.manyTableData = res.data
      } else if (this.activeName === 'only') {
        // 静态参数数据
        this.onlyTableData = res.data
      }
    },
    // 切换动态参数和静态属性
    handleTabClick() {
      this.handleCateChanged()
    },
    // 添加参数按钮 弹出对话框
    addParamsBtn() {
      this.addParamsVisible = true
    },
    // 添加参数对话框的确定按钮
    addParamsInfo() {
      // 对对话框的内容进行预验证
      this.$refs.addParamsRef.validate(async (valid) => {
        if (!valid) return
        // 发送添加参数的请求
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addParamsForm.attr_name,
            attr_sel: this.activeName,
          }
        )
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        // 让对话框隐藏
        this.addParamsVisible = false
        // 刷新列表
        this.handleCateChanged()
      })
    },
    // 关闭添加参数对话框之前的重置
    addParamsClosed() {
      this.$refs.addParamsRef.resetFields()
    },
    // 添加新的三级参数按钮
    newTagBtn(row) {
      row.inputBtn = true
      // 让文本框自动获得焦点
      // $nextTick 方法的作用，就是当页面上元素被重新渲染之后，才会指定回调函数中的代码
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 新的三级参数框失去焦点
    async handleInputConfirm(row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputBtn = false
        return
      }
      // 如果没有return 需要对后续数据进行处理
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputBtn = false
      // 发起修改参数的请求
      this.saveAttrVals(row)
    },
    // 发起修改参数的请求
    async saveAttrVals(row) {
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' '),
        }
      )
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
    },
    // 删除tag
    closeTag(index, row) {
      row.attr_vals.splice(index, 1)
      this.saveAttrVals(row)
    },
    // 修改参数按钮
    async editParamsBtn(attr_id) {
      // 发送获取原始数据的请求
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes/${attr_id}`,
        {
          params: {
            attr_sel: this.activeName,
          },
        }
      )
      this.editParamsForm = res.data
      this.editParamsVisible = true
    },
    // 编辑参数对话框的确定按钮
    editParamsInfo() {
      // 对对话框的内容进行预验证
      this.$refs.editParamsRef.validate(async (valid) => {
        if (!valid) return
        // 发送添加参数的请求
        const { data: res } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.editParamsForm.attr_id}`,
          {
            attr_name: this.editParamsForm.attr_name,
            attr_sel: this.activeName,
          }
        )
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        // 让对话框隐藏
        this.editParamsVisible = false
        // 刷新列表
        this.handleCateChanged()
      })
    },
    // 关闭添加参数对话框之前的重置
    editParamsClosed() {
      this.$refs.editParamsRef.resetFields()
    },
    // 删除参数按钮
    async deleteParamsBtn(attr_id) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该商品, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      if (confirmResult !== 'confirm') return this.$message.info('已取消删除！')
      // 发送确定删除的请求
      const { data: res } = await this.$http.delete(
        `categories/${this.cateId}/attributes/${attr_id}`
      )
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      // 刷新列表
      this.handleCateChanged()
    },
  },
  computed: {
    // 设置添加参数按钮是否禁用
    isDisabled() {
      if (this.selectedKeys.length !== 3) {
        return true
      } else {
        return false
      }
    },
    // 通过计算属性 获取所选择的第三级分类的id
    cateId() {
      if (this.selectedKeys.length === 3) {
        return this.selectedKeys[this.selectedKeys.length - 1]
      }
      return null
    },
    // 添加参数的title
    titleText() {
      if (this.activeName === 'many') {
        return '动态参数'
      }
      return '静态属性'
    },
  },
}
</script>


<style lang="less" scoped>
.el-cascader {
  margin-top: 14px;
  margin-bottom: 14px;
  width: 200px;
}
.el-tag {
  margin: 0 10px;
}
.new_input {
  width: 120px;
}
</style>